﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using BabyShop.WebSite.Models;

namespace BabyShop.WebSite.Services
{
    public class ProductService : BaseService<Product>
    {
        public IList<Product> GetAllProduct()
        {
            return DataServices.Products.Where(p => !p.CommonColumns.IsDelete).ToList();
        }

        public Product GetProduct(Guid productGuid)
        {
            return DataServices.Products.FirstOrDefault(p => p.ProductGuid == productGuid && !p.CommonColumns.IsDelete);
        }

        public IDictionary<string, string> GetImgListFromIntro(string productIntro)
        {
            IDictionary<string, string> imgSelectItems = new Dictionary<string, string>();
            const string regImg = @"<img.*?src\s*=\s*(""|')?(?<src>.*?)(""|')?(\s|>)";
            Regex imgRegex = new Regex(regImg, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            var allImgMatchs = imgRegex.Matches(productIntro);
            foreach (Match imgMatch in allImgMatchs) {
                if (imgMatch.Success && !imgMatch.Groups["src"].Value.StartsWith("data:"))
                    imgSelectItems.Add(imgMatch.Groups["src"].Value, imgMatch.Groups["src"].Value);
            }

            return imgSelectItems;
        }

        public override bool Save(Product entity, Guid modifiedBy) {
            bool saveSucc = base.Save(entity, modifiedBy);
            if(saveSucc) {
                SerialNumberService serialNumberService = new SerialNumberService();
                saveSucc = serialNumberService.SetSerialNumberInValid(DateTime.Now.Date, modifiedBy, "Product");
            }
            return saveSucc;
        }
    }
}